import axios from 'axios'

// 获取请求头（带 token）
const getHeaders = () => {
    const headersJson = localStorage.getItem('requestHeaders')
    try {
        return JSON.parse(headersJson) || {}
    } catch (e) {
        console.warn('请求头解析失败:', e)
        return {}
    }
}

// 创建 Axios 实例
const instance = axios.create({
    baseURL: '', // 可配置基础路径
    timeout: 10000
})

// 请求拦截器（设置 headers）
instance.interceptors.request.use(config => {
    config.headers = {
        ...config.headers,
        ...getHeaders()
    }
    return config
})

// 响应拦截器（统一错误处理）
instance.interceptors.response.use(
    response => response.data,
    error => {
        const msg = error.response?.data?.message || '请求失败'
        return Promise.reject(new Error(msg))
    }
)

const request = {
    get(url, params = {}) {
        return instance.get(url, { params })
    },

    post(url, data = {}) {
        return instance.post(url, data)
    },

    put(url, data = {}) {
        return instance.put(url, data)
    },

    delete(url, data = {}) {
        return instance.delete(url, { data })
    }
}

export default request